#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "common.h"

unsigned int sum; // Global variable definition

void * runner(void * param)
{
    int upper = atoi(param);

    sum = 0;

    for (unsigned int i = 1; i <= upper; i++)
    {
        sum += i;
    }

    pthread_exit(0); // Child thread exits
}

int main(int argc, char * argv[])
{
    pthread_t tid;
    pthread_attr_t attr;

    if (argc != 2) // Notice that count included the executable file name.
    {
        fprintf(stderr, "Usage: *executable file name* <integer value>");
        stderr_br(1);

        return -1;
    }

    int param = atoi(argv[1]);
    if (param < 0)
    {
        fprintf(stderr, "%d must be >= 0", param);
        stderr_br(1);

        return -1;
    }

    pthread_attr_init(&attr);
    pthread_create(&tid, &attr, runner, argv[1]); // Thread creation
    pthread_join(tid, NULL); // Main (parent) thread waiting for exit of child thread
    printf("Sum = %d", sum);
    br(1);

    return 0;
}
